<?php

class ClassesController extends BaseController {

    public function index() {

        $Options = Cache::get('options');
        $aData   = array(
            'sPage_Title'       => trans('navigation.classes'),
            'sPage_Description' => trans('navigation.classes-description'),
            'aTeams'            => $Options['NGANH'],
            'aLevels'           => $Options['CAP'],
            'aCrews'            => $Options['DOI'],
        );

        return View::make("classes.page", $aData);
    }

    public function postAjaxClassList() {
        $aResponse = array();

        if (Request::get('sAction') && Request::get('sGroupActionName')) {

            $aResponse['Classes'] = array();

            switch (Request::get('sGroupActionName')) {
                case 'delete':
                    foreach (Classes::whereIn('id', Request::get('id'))->get() as $oClasses) {
                        if (count($oClasses->user)) {
                            $aResponse['Classes'][] = $oClasses->generateClassName();
                        } else {
                            $oClasses->delete();
                        }
                    }

                    if (empty($aResponse['Classes'])) {
                        $aResponse['sMessage'] = trans('classes-pages.message.delete-success');
                    } else {
                        $aResponse['sMessage'] = trans('classes-pages.message.delete-error') . '<ul><li>' . implode("</li><li>", $aResponse['Classes']) . '</li></ul>';
                    }

                    break;

                default:
                    break;
            }
        }

        // <editor-fold defaultstate="collapsed" desc="Filter Data">
        /* Individual column filtering */
        $aClasses = DB::table('classes');

        $aColumns = array('course', 'team', 'level', 'crew', 'location');
        foreach ($aColumns as $sColumnName) {
            if (Request::get('filter_' . $sColumnName)) {

                $aClasses->where($sColumnName, 'like', '%' . Request::get('filter_' . $sColumnName) . '%');
            }
        }

        /*
         * Ordering
         */
        $aColumns = array('id', 'course', 'team', 'level', 'crew', 'location', 'note', 'actions');
        if (Request::get('iSortCol_0')) {
            for ($i = 0; $i < Request::get('iSortingCols'); $i++) {
                if (Request::get('bSortable_' . Request::get('iSortCol_' . $i)) == "true") {
                    $aClasses->orderBy($aColumns[Request::get('iSortCol_' . $i)], Request::get('sSortDir_' . $i) === 'asc' ? 'asc' : 'desc');
                }
            }
        }

        $iTotalRecords = $aClasses->count();

        /*
         * Paging
         */
        if (Request::get('iDisplayLength') != '-1') {
            $aClasses->skip(Request::get('iDisplayStart'))->take(Request::get('iDisplayLength'));
        }

        $aClasses = $aClasses->get();
        $aOptions = array();
        $aTemp    = Options::whereIn('type', array('NGANH', 'CAP', 'DOI'))->get();

        foreach ($aTemp as $oValue) {
            $aOptions[$oValue->type][$oValue->key] = $oValue->data;
        }

        foreach ($aClasses as $key => $oClasses) {
            $aClasses[$key]->team     = isset($aOptions['NGANH'][$oClasses->team]) ? $aOptions['NGANH'][$oClasses->team] : $oClasses->team;
            $aClasses[$key]->level    = isset($aOptions['CAP'][$oClasses->level]) ? $aOptions['CAP'][$oClasses->level] : $oClasses->level;
            $aClasses[$key]->crew     = isset($aOptions['DOI'][$oClasses->crew]) ? $aOptions['DOI'][$oClasses->crew] : null;
            $aClasses[$key]->checkbox = '<input type="checkbox" name="id[]" value="' . $oClasses->id . '">';
            $aClasses[$key]->actions  = '
                <button class="btn btn-xs default btn-viewuser"  data-href="' . route('class-detail-user', array('id' => $oClasses->id)) . '"><i class="fa fa-search"></i> ' . trans('system.button.view') . '</button>
                <button class="btn btn-xs default btn-class-edit '. CNamHoa::getHideClass('class-edit', ['addClass' => 'hide']) .'" data-href="' . route('class-edit', array('id' => $oClasses->id)) . '"><i class="fa fa-pencil"></i> ' . trans('system.button.edit') . '</button>';
        }

        $aResponse = $aResponse + array(
            "iTotalRecords"        => DB::table('classes')->count(),
            "iTotalDisplayRecords" => $iTotalRecords,
            "sEcho"                => Request::get('sEcho'),
            'aaData'               => $aClasses
        );
        // </editor-fold>

        return Response::json($aResponse);
    }

    function getAjaxCreateClass() {

        $Options = Cache::get('options');
        $aData   = array(
            'aCourse' => $Options['COURSE'],
            'aTeams'  => $Options['NGANH'],
            'aLevels' => $Options['CAP'],
            'aCrews'  => $Options['DOI'],
        );

        return View::make("classes.new", $aData);
    }

    function postAjaxCreateClass() {
        try {
            Classes::create(array(
                'course'   => Input::get('course'),
                'team'     => Input::get('team'),
                'level'    => Input::get('level'),
                'crew'     => Input::get('crew'),
                'location' => Input::get('location'),
                'note'     => Input::get('note'),
                'updater'  => Auth::user()->id,
            ));
            $aResponse = array(
                'status'  => 200,
                'message' => trans('classes-pages.message.create-success'),
            );
        } catch (Exception $exc) {

            $aResponse = array(
                'status'  => 0,
                'message' => trans('classes-pages.message.create-error'),
            );
        }
        return Response::json($aResponse);
    }

    function getAjaxDetailUser($id) {
        $oClasses = Classes::find($id);

        return View::make("classes.user", array(
                'ClassInfo'  => $oClasses,
                'sClassName' => $oClasses->generateClassName(),
                'Users'      => $oClasses->user()->orderBy('id')->get()
        ));
    }

    function postAjaxRemoveUser() {

        $aResponse = array(
            'status'  => 200,
            'user_id' => Request::get('user_id'),
        );

        if (Request::get('class_id') && Request::get('user_id')) {
            Classes::find(Request::get('class_id'))->user()->detach(Request::get('user_id'));
        } else {
            $aResponse['status'] = 0;
        }

        return Response::json($aResponse);
    }

    function getAjaxUpdateClass($id) {

        $oClasses = Classes::find($id);
        $aData    = array(
            'oClasses'   => $oClasses,
            'sClassName' => $oClasses->generateClassName(),
        );

        return View::make("classes.edit", $aData);
    }

    function postAjaxUpdateClass($id) {

        try {
            $oClasses           = Classes::find($id);
            $oClasses->location = Input::get('location');
            $oClasses->note     = Input::get('note');
            $oClasses->updater  = Auth::user()->id;
            $oClasses->save();
            $aResponse          = array(
                'status'  => 200,
                'message' => trans('classes-pages.message.update-success'),
            );
        } catch (Exception $exc) {

            $aResponse = array(
                'status'  => 0,
                'message' => trans('classes-pages.message.update-error'),
            );
        }

        return Response::json($aResponse);
    }

}
